package com.edais.service.imp.sina;

import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.edais.dao.CenterDao;
import com.edais.dao.OptionDao;
import com.edais.dao.UserDao;
import com.edais.domain.IdcardInfo;
import com.edais.mina.TcpMinaClient;
import com.edais.service.OptionService;
import com.edais.service.sina.SinaHostingService;
import com.edais.util.CommonUtil;
import com.edais.util.IDCard;
import com.edais.util.JsonUtil;
import com.edais.util.ThirdPartyEnvUtil;
import com.edais.util.RSAThirdParty.RSA;

@Service

@Transactional(propagation=Propagation.SUPPORTS,readOnly=true)
public class SinaHostingServiceImp implements SinaHostingService {
	private static final Log logger = LogFactory.getLog(SinaHostingServiceImp.class);

	@Autowired
	private UserDao userDao;
	
	@Autowired
	private OptionDao optionDao;
	
	@Autowired
	private CenterDao centerDao;
	
	@Autowired
	private OptionService optionService;

	@Override
	@Transactional(propagation=Propagation.REQUIRED,rollbackFor=Exception.class,readOnly=false)
	public boolean setSinaRealName(Map<String,Object> mapParam) throws Exception {
		// 判断该身份证是否已经被使用，一个身份证只能用一次
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("identitynum", mapParam.get("identitynum"));
		int count = userDao.checkIdCardIsExist(map);
		if(count >0 ){
			return false;
		}
		
		// 实名信息
		// 请求参数封装
		Map<String, String> paramMap = new HashMap<String,String>();
		paramMap.put("cardNo", String.valueOf(mapParam.get("identitynum")));//身份证号
		paramMap.put("cardName", String.valueOf(mapParam.get("realname")));//姓名
		
		String requestParam = "keyRandom=KEY_RANDOM";
		String publicKeyParam="";
		try {
			publicKeyParam = RSA.getPublick_Key_Encrypt(paramMap);
			requestParam = requestParam.replace("KEY_RANDOM", URLEncoder.encode(publicKeyParam, "utf-8"));
		} catch (Exception e) {
			logger.debug("公钥加密串："+e);
		}
		
		//第三方工程请求url
		String url = ThirdPartyEnvUtil.getValue("queryIdCardUrl");
		//实名认证
		String setRealNameResult = CommonUtil.sendPostByHttp(url, requestParam);
		if( null == setRealNameResult ){
			logger.error("设置实名信息失败");
			throw new RuntimeException("实名认证失败");
		}else{
			//解析发送结果
			Map setRealNameResultMap = JsonUtil.getMapFromJsonString(setRealNameResult);
			if(null == setRealNameResultMap  || "sysException".equals(setRealNameResultMap.get("rescode"))){
				// 系统异常
				logger.error("设置实名信息失败:" + String.valueOf(setRealNameResultMap.get("resmsg_cn")));
				throw new RuntimeException("实名认证失败");
			}else if("BusinessException".equals(setRealNameResultMap.get("rescode"))){
				// 业务异常，把错误信息提示给用户
				logger.error("设置实名信息失败:" + String.valueOf(setRealNameResultMap.get("resmsg_cn")));
				throw new RuntimeException(String.valueOf(setRealNameResultMap.get("resmsg_cn")));
			}
		}
		
		//用户身份证认证表
		IdcardInfo idCardInfo = new IdcardInfo();
		
		//身份认证通过
		optionDao.updateIdCardValidate("Y",null,"Y", mapParam.get("userId").toString());
		idCardInfo.setIdno(mapParam.get("identitynum").toString());//身份证
		idCardInfo.setName(mapParam.get("realname").toString());//真实姓名
		idCardInfo.setUser_id(Integer.valueOf(mapParam.get("userId").toString()));
		//性别
		String sex = IDCard.getSex(mapParam.get("eightcardid").toString());
		idCardInfo.setGender(sex);
		//生日
		String date = IDCard.getBirthDay(mapParam.get("eightcardid").toString());;
		SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
		Date birthDay = format.parse(date);
		idCardInfo.setBirth(birthDay);
		
		//更改身份信息
		centerDao.modifyUserInfoCd(idCardInfo.getBirth(),
			idCardInfo.getGender(), idCardInfo.getIdno(),
			idCardInfo.getName(), idCardInfo.getUser_id());
		
		//保存用户身份证认证表
		optionDao.insertIdCardInfo(idCardInfo);
		return true;
	}
	
	/**
	 * 修改主账户信息
	 * @throws Exception
	 */
	public String updAccount(Map<String,Object> map,String userId) throws Exception{
		// 设置报文体报文数据
		String transCode = "E300024";
		map.put("userid", userId);
		map.put("identitynum", map.get("identitynum"));
		map.put("username", map.get("realname"));

		// 设置报文体报文数据
		String jsonStr = CommonUtil.constructJsonStr(transCode, userId, map);// 构建json字符串
		TcpMinaClient tcpMinaClient = new TcpMinaClient();
		String rtnStr = tcpMinaClient.sendMessage(jsonStr);

		if(StringUtils.isBlank(rtnStr)){
			logger.error("调用核心接口E300024发生异常");
			return "fail";
		}
		
		rtnStr = rtnStr.substring(8, rtnStr.length());
		// 转化json数据为页面模型数据格式
		Map rtnMap = (HashMap) JsonUtil.getObjectFromJsonString(rtnStr,HashMap.class);
		
		if (rtnMap == null || (!"00000".equals(rtnMap.get("rescode")) && !"user.identityno.has.registed".equals(rtnMap.get("resmsg")))) {
			logger.error("修改主账户E300024异常:" + rtnMap.get("resmsg"));
			return "fail";
		}
		return "success";
	}
	
	@Override
	@Transactional(propagation=Propagation.REQUIRED,rollbackFor=Exception.class,readOnly=false)
	public void bindingVerify(Map<String,Object> mapParam) throws Exception {
		mapParam.put("sinaIdcardValidate", "Y");
		int count = userDao.updSinaIdcardValidate(mapParam);
		if(count == 0){
			//更新身份证是否通过验证(Y/N)标志失败
			logger.error("更新[新浪托管身份绑定是否完成]字段状态失败");
			throw new RuntimeException("更新[新浪托管身份绑定是否完成]字段状态失败");
		}
		
		// sina绑定认证信息
		// 请求参数封装
		Map<String, String> paramMap = new HashMap<String,String>();
		paramMap.put("userId", String.valueOf(mapParam.get("depositDockUserid")));
		paramMap.put("verifyEntity", String.valueOf(mapParam.get("mobile")));
//		String param = CommonUtil.getHttpParameterFromMap(paramMap);
//		logger.debug("sina绑定认证信息请求参数："+param);
		
		String requestParam = "keyRandom=KEY_RANDOM";
		String publicKeyParam="";
		try {
			publicKeyParam = RSA.getPublick_Key_Encrypt(paramMap);
			requestParam = requestParam.replace("KEY_RANDOM", URLEncoder.encode(publicKeyParam, "utf-8"));
		} catch (Exception e) {
			logger.debug("公钥加密串："+e);
		}
		
		//第三方工程请求url
		String url = ThirdPartyEnvUtil.getValue("bindingVerifyUrl");
		//发送短信消息
		String bindingVerifyResult = CommonUtil.sendPostByHttp(url, requestParam);
		if( null == bindingVerifyResult ){
			logger.error("sina绑定认证信息失败");
			throw new RuntimeException("实名认证失败");
		}else{
			//解析发送结果
			Map bindingVerifyResMap = JsonUtil.getMapFromJsonString(bindingVerifyResult);
			if(null == bindingVerifyResMap  || "sysException".equals(bindingVerifyResMap.get("rescode"))){
				// 系统异常
				logger.error("sina绑定认证信息失败:" + String.valueOf(bindingVerifyResMap.get("resmsg_cn")));
				throw new RuntimeException("实名认证失败");
			}else if("BusinessException".equals(bindingVerifyResMap.get("rescode"))){
				// 业务异常，把错误信息提示给用户
				logger.error("sina绑定认证信息失败:" + String.valueOf(bindingVerifyResMap.get("resmsg_cn")));
				throw new RuntimeException(String.valueOf(bindingVerifyResMap.get("resmsg_cn")));
			}
		}
				
		/*Map<String, String> map = new SinaHostingFuntions().bindingVerify(
				mapParam.get("userId").toString(), mapParam.get("mobile").toString());
		if (map == null || !"APPLY_SUCCESS".equals(map.get("code"))) {
			logger.error("绑定认证信息失败");
			throw new RuntimeException("绑定认证信息失败");
		}*/
	}

	@Override
	@Transactional(propagation=Propagation.REQUIRED,rollbackFor=Exception.class,readOnly=false)
	public void createMainAcount(Map<String,Object> mapParam) throws Exception {
		if(!"success".equals(optionService.createAccount(mapParam,mapParam.get("userId").toString()))){
			logger.error("创建主账户失败");
			throw new RuntimeException("创建主账户失败");
		}
	}
	
	@Override
	@Transactional(propagation=Propagation.REQUIRED,rollbackFor=Exception.class,readOnly=false)
	public void updMainAcount(Map<String,Object> mapParam) throws Exception {
		optionDao.updateIdCardValidate(null,"Y","Y", mapParam.get("userId").toString());
		
		if(!"success".equals(updAccount(mapParam,mapParam.get("userId").toString()))){
			logger.error("修改主账户失败");
			throw new RuntimeException("修改主账户失败");
		}
	}
}
